﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace common.Controls
{
    public partial class downloader : UserControl
    {
        public downloader()
        {
            InitializeComponent();
        }

        public delegate void StreamAvailDelegate(Stream stream);

        public event StreamAvailDelegate StreamAvailible = null;

        public void Download(Uri uri)
        {
            WebClient client = new WebClient();
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            client.AllowReadStreamBuffering = true;
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
            client.OpenReadAsync(uri);
        }

        void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (StreamAvailible != null)
                {
                    StreamAvailible(e.Result);
                }
            }
        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            progress.ScaleX = e.ProgressPercentage / 100.0;
        }
    }
}
